<template>
  <div class="research-box">
    <div style="margin-bottom: 16px">
      <t-button @click="addGoodInfo"><i class="doorIcon addDoorIcon">&#xe662;</i> <span>添加文创商品</span> </t-button>
    </div>
    <!-- <t-row :gutter="16" style="margin: 0px；marginBottom:16px;">
      <t-col :span="6" style="margin-bottom: 0">
        <t-button @click="addGoodInfo"
          ><i class="doorIcon addDoorIcon">&#xe662;</i> <span>添加文创商品</span>
        </t-button>
        <span class="title">添加此展览相关文创商品</span>
      </t-col>
    </t-row> -->
    <div class="center-box">
      <t-table
        :fixedRows="[0, 0]"
        maxHeight="750px"
        row-key="index"
        :data="list"
        :columns="BUY_COLUMNS1"
        :resizable="false"
      >
        <template #coverUrl="{ row }">
          <img :src="urls + row.coverUrl + webUrls1" fit="cover" position="center" class="table-img" />
        </template>
        <template #id="{ row }">
          <div class="hw-flex-style-c-a-r hw-click-cursor">
            <span @click="getDelId(row.id)">移除</span>
            <span @click="addGoodInfo(row)">编辑</span>
          </div>
        </template>
        <template #price="{ row }">
          <span v-if="row.price">￥{{ row.price }}</span>
          <span v-else>暂无价格</span>
        </template>
        <template #empty>
          <div class="hw-flex-style-c-c-c hw-box-style-flex-clm null-box-style">
            <img class="null-img-1" :src="publicUrls + 'assets/img/currentNull.png'" alt="" />
            <span class="null-title-1">暂无文创商品</span>
          </div>
        </template>
      </t-table>
    </div>
    <t-row v-if="total > 10">
      <t-col :span="12" class="bottom-mg">
        <t-pagination
          v-model="parmas.pageNo"
          v-model:pageSize="parmas.pageSize"
          :total="total"
          show-sizer
          :show-page-size="true"
          :page-size-options="pageSizeOptions"
          @page-size-change="onPageSizeChange"
          @current-change="onCurrentChange"
        />
      </t-col>
    </t-row>
    <div class="form-boxs">
      <t-form
        ref="form"
        :rules="rules"
        :data="formData"
        :colon="true"
        @submit="onSubmit"
        label-width="0"
        v-if="visible1"
      >
        <t-dialog
          placement="center"
          header="添加文创商品"
          :visible="visible1"
          :confirm-on-enter="true"
          :on-cancel="closetable"
          :on-close="closetable"
          :cancelBtn="null"
          :confirmBtn="null"
          :loading="loading"
        >
          <template #body>
            <div class="from-body-box">
              <t-form-item label="商品名称" name="name">
                <div class="hw-from-content">
                  <div class="from-title-box">
                    <span class="from-title-box-name">商品名称</span>
                  </div>
                  <t-input
                    @change="namechange"
                    v-model="formData.name"
                    :maxlength="30"
                    placeholder="请输入商品名称,最大30字"
                  ></t-input>
                </div>
              </t-form-item>

              <t-form-item name="coverUrl">
                <div class="hw-from-content">
                  <div class="from-title-box">
                    <span class="from-title-box-name">商品封面</span>
                  </div>
                  <t-upload
                    ref="uploadRef1"
                    v-loading="uploadLoading"
                    :allowUploadDuplicateFile="true"
                    :size-limit="{ size: 5, unit: 'MB' }"
                    :max="1"
                    accept=".jpg,.png"
                    :before-upload="beforeUpload"
                    :upload-all-files-in-one-request="uploadAllFilesInOneRequest"
                  >
                    <div class="upload-box">
                      <div class="img-list-box-upload" v-if="!formData.coverUrl">
                        <t-icon name="add" size="24px" style="color: rgba(0, 0, 0, 0.38)"></t-icon>
                        <span> 点击上传图片 </span>
                      </div>
                      <!-- <img v-if="!formData.coverUrl" src="../../../../../assets/user/uer3.png" alt="" /> -->
                      <img
                        v-else
                        :src="urls + formData.coverUrl + webUrls"
                        fit="cover"
                        position="center"
                        class="image-boxs"
                      />
                    </div>
                  </t-upload>
                  <span class="audio-tip">支持2M以内JPG、PNG图片，可稍后上传</span>
                </div>
              </t-form-item>

              <t-form-item label="" name="price">
                <div class="hw-from-content">
                  <div class="from-title-box">
                    <span class="from-title-box-name">商品价格</span>
                  </div>
                  <t-input-adornment prepend="￥">
                    <t-input-number
                      style="width: 136px"
                      placeholder="请输入商品价格"
                      v-model="formData.price"
                      theme="normal"
                      :max="'99999'"
                      :min="'0'"
                    ></t-input-number>
                  </t-input-adornment>
                </div>
              </t-form-item>
              <t-form-item label="商品名称" name="url">
                <div class="hw-from-content">
                  <div class="from-title-box">
                    <span class="from-title-box-name">商品链接</span>
                  </div>
                  <t-input v-model="formData.url" :maxlength="240" placeholder="请输入商品链接"></t-input>
                </div>
              </t-form-item>
            </div>
            <!-- <t-row :gutter="16">
            <t-col :span="6">
              <span class="from-title">商品名称</span>
              <t-form-item label="商品名称" name="name">
                <t-input v-model="formData.name" placeholder="请输入商品名称"></t-input>
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <span class="from-title">商品价格</span>
              <t-form-item label="商品名称" name="price">
                <t-input-number
                  placeholder="请输入商品价格"
                  v-model="formData.price"
                  theme="normal"
                  :max="9999"
                  :min="0"
                ></t-input-number>
              </t-form-item> 
            </t-col>
            <t-col :span="6">
              <span class="from-title">商品图片</span>
              <t-form-item name="coverUrl" label="项目封面" help="支持2M以内JPG、PNG图片，可稍后上传">
                <t-upload
                  ref="uploadRef1"
                  :allowUploadDuplicateFile="true"
                  :size-limit="{ size: 2, unit: 'MB' }"
                  :max="1"
                  accept="image/*"
                  :before-upload="beforeUpload"
                  :upload-all-files-in-one-request="uploadAllFilesInOneRequest"
                >
                  <div class="upload-box">
                    <img v-if="!formData.coverUrl" src="../../../../../assets/user/uer3.png" alt="" />
                    <img
                      v-else
                      :src="urls + formData.coverUrl + webUrls"
                      fit="cover"
                      position="center"
                      class="image-boxs"
                    />
                  </div>
                </t-upload>
              </t-form-item>
            </t-col>
            <t-col :span="12">
              <span class="from-title">商品链接</span>
              <t-form-item label="商品名称" name="url">
                <t-input v-model="formData.url" placeholder="请输入商品链接"></t-input>
              </t-form-item>
            </t-col>
          </t-row> -->
          </template>
          <template #footer>
            <t-button @click="closetable" theme="default" variant="outline">取消</t-button>
            <t-button type="submit">确定</t-button>
          </template>
        </t-dialog>
      </t-form>
    </div>
    <messageModel
      submitText="删除"
      title="提示"
      :visible="visibleMessage"
      problem="确定删除此商品？"
      message="删除后可重新添加"
      @closeClick="delerror"
      @submitClick="delSuccess"
    />
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { publicUrls } from '@/utils/minxin';
import messageModel from '@/components/messageModel/index.vue';
import { upLoadFn } from '@/utils/request/upload';
import { goodsSave, goodsDelete, goodsList } from '@/api/goods/goods';
import { url, heards, urls } from '@/utils/request/upload';
import { ref, reactive } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { BUY_COLUMNS1, dataList1 } from './data';

const webUrls: string = '?imageView2/2/w/120/h/120/format/webp';
const webUrls1: string = '?imageView2/2/w/48/h/48/format/webp';
const pageSizeOptions = [
  { label: '每页 10 条', value: 10 },
  { label: '每页 20 条', value: 20 },
  { label: '每页 50 条', value: 50 },
  { label: '每页 100 条', value: 100 },
];
const visibleMessage = ref(false);
const uploadLoading = ref(false);
const delId = ref(null);
const visible1 = ref(false);
const loading = ref(false);
const uploadAllFilesInOneRequest = ref(false);
const list = ref([]);
const formData = reactive({
  id: 0,
  url: '',
  name: '',
  coverUrl: '',
  price: 0,
});
const parmas = reactive({
  value: '',
  pageNo: 1,
  pageSize: 20,
});

const total = ref(0);
const rules = {
  name: [{ required: true, message: '名称必填', type: 'error' }],
  coverUrl: [{ required: true, message: '封面必填', type: 'error' }],
  // url: [{ required: true, message: '链接必填', type: 'error' }],
  // price: [{ required: true, message: '价格必填', type: 'error' }],
};
const namechange = () => {
  //监听空格输入

  formData.name = formData.name.replace(/\s/g, '');
};
const init = async () => {
  try {
    if (loading.value) {
      return;
    }
    loading.value = true;
    let res = await goodsList(localStorage.getItem('projectId'), parmas);
    total.value = res.data.total;
    list.value = res.data.data;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};
const addGoodInfo = (e?: any) => {
  formData.id = e ? e.id : 0;
  formData.url = e ? e.url : '';
  formData.name = e ? e.name : '';
  formData.coverUrl = e ? e.coverUrl : '';
  formData.price = e & (e !== 0) ? e.price : null;
  visible1.value = true;
};
const closetable = () => {
  visible1.value = false;
};
const onSubmit = ({ validateResult, firstError }) => {
  // if (formData.url) {
  //   if (formData.url.indexOf('http/') == -1) {
  //     MessagePlugin.warning('请填写正确链接');
  //     return;
  //   }
  // }
  if (formData.url) {
    let urlType = isURL(formData.url);
    if (!urlType) {
      MessagePlugin.warning('请填写正确链接');
      return;
    }
  }
  if (formData.price) {
    if (formData.price > 9999999.99) {
      MessagePlugin.warning('价格不得大于9999999.99');
      return;
    }
  }

  if (validateResult === true) {
    // MessagePlugin.success('提交成功');
    saveGoods();
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
    MessagePlugin.warning(firstError);
  }
};

const isURL = (input) => {
  // 匹配URL的正则表达式
  var urlPattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;

  // 判断输入是否匹配正则表达式
  return urlPattern.test(input);
};
const saveGoods = async () => {
  try {
    if (loading.value) {
      return;
    }
    loading.value = true;
    let res = await goodsSave(localStorage.getItem('projectId'), formData);
    if (res.statusCode == 200) {
      MessagePlugin.success('操作成功');
      visible1.value = false;
    } else {
      MessagePlugin.error(JSON.parse(res.errors));
    }
    loading.value = false;
    init();
  } catch {
    loading.value = false;
  }
};
const delSuccess = () => {
  deleteGoods(delId.value);
  visibleMessage.value = false;
};
const delerror = () => {
  visibleMessage.value = false;
};
const getDelId = (e: number) => {
  delId.value = e;
  visibleMessage.value = true;
};
const deleteGoods = async (e: number) => {
  try {
    if (loading.value) {
      return;
    }
    loading.value = true;
    let res = await goodsDelete(localStorage.getItem('projectId'), e);
    if (res.statusCode == 200) {
      MessagePlugin.success('删除成功');
    }
    loading.value = false;
    init();
  } catch {
    loading.value = false;
  }
};
const onPageSizeChange = (size) => {
  parmas.pageNo = 1;
  init();
};
const onCurrentChange = (index, pageInfo) => {
  //分页事件
  init();
};

const beforeUpload = (file: any) => {
  if (file.name.indexOf('.png') == -1 && file.name.indexOf('.jpg') == -1) {
    MessagePlugin.error('文件类型不支持');
    return;
  }
  //回调钩子
  if (file.type.indexOf('image/') == -1) {
    MessagePlugin.error('文件类型错误');
    return;
  }
  if (file.size / 1048576 > 2) {
    MessagePlugin.error('上传大小超出2M限制');
    return;
  }
  uploadLoading.value = true;
  upLoadFn(file, 5).then((res) => {
    // console.log(res);
    if (res) {
      formData.coverUrl = res;
      console.log(urls + formData.coverUrl + webUrls);
      // formData.coverUrl = res;
    } else {
      MessagePlugin.error('创建成功');
    }
    uploadLoading.value = false;
  });
};
init();
</script>

<style lang="less" scoped>
.title {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.4);
  line-height: 32px;
  margin-left: 16px;
}
.hw-flex-style-c-a-r {
  justify-content: flex-end;
  span {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #e62b17;
    line-height: 24px;
    margin-left: 16px;
  }
}
.from-title {
  display: flex;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.9);
  line-height: 22px;
  margin-bottom: 12px;
}
.upload-box {
  width: 120px;
  height: 120px;
  margin-right: 20px;

  img {
    width: 120px;
    height: 120px;
    border-radius: 3px;
  }
  .image-boxs {
    width: 120px;
    height: 120px;
    border-radius: 3px;
  }
}
.table-img {
  width: 48px;
  height: 48px;
  border-radius: 2px;
}
.t-col {
  margin-bottom: 20px;
}
:deep(.t-input-adornment) {
  width: 100%;
}
.t-input-number {
  width: 100%;
}
.research-box {
  height: 98%;
  display: flex;
  flex-direction: column;
  padding: 0 24px;
  // overflow: auto;
}
.center-box {
  flex: 1;
  overflow: auto;
  :deep(.t-table) {
    max-height: 100%;
    height: 100%;
  }
  :deep(.t-table__content) {
    max-height: 100% !important;
  }
}
:deep(.t-table__empty) {
  border-bottom: none;
}
:deep(.t-table__content) {
  // border: 1px solid #ddd;
  border-bottom: none;
}
.addDoorIcon {
  font-size: 16px;
  color: #fff;
  margin-right: 6px;
}
:deep(.t-table__header tr) {
  background: #f5f5f5;

  height: 48px;
}
.from-body-box {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding-bottom: 16px;
  max-height: 480px;
  scrollbar-width: none;
}
.from-body-box::-webkit-scrollbar {
  display: none;
}
.form-boxs {
  :deep(.t-dialog) {
    width: 632px;
  }
  :deep(.t-dialog__header) {
    height: 60px;
    box-shadow: none;
  }
  :deep(.t-dialog__body) {
    padding: 0 24px;
  }
}

:deep(.t-input-adornment__text) {
  font-size: 16px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.26);
  line-height: 22px;
}
.audio-tip {
  display: flex;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.38);
  line-height: 22px;
  margin-top: 8px;
}
.img-list-box-upload {
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 120px;
  background: #fafafa;
  border-radius: 4px;
  border: 1px dashed #ebe4e3;
  span {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.38);
    line-height: 22px;
  }
}
 
.img-list-box-upload:hover {
  border-color: #e62b17;
}
:deep(.t-table__empty-row) {
  background: transparent !important;
}
.bottom-mg {
  margin-bottom: 0px !important;
}
.null-title-1{
  color: rgba(0, 0, 0, 0.38);
}
</style>
